#!/bin/bash
source tools/getenv.sh

# 当前和 mySystemdServiceStop 方法是一样的内容，现在都是用ps去匹配的
function mySupervisorServiceStop() {
  echo -e "$BOLD_WHITE 判断服务进程是否存在...$RESET"
  num=$(getServerBinAllPathNum)
  if [[ $num -eq 0 ]]; then
    echo -e "${GREEN}进程不存在，无需处理...$RESET"
  else
    echo -e "${GREEN}进程存在$RESET"
    echo -e "=========================== $GREEN 进程存在,stop...$RESET ==========================="
    echo  "开始stop..."
    oldPid=$(cat "$PID_FILE")
    echo -e "$RED 旧进程id： $oldPid $RESET"
    kill -9 "$oldPid"
    echo "停止完成"
    num=$(getServerBinAllPathNum)
    if [[ "$num" -eq 0 ]]; then
      echo  -e "${GREEN}进程kill成功，现在不存在...$RESET"
    else
      echo  -e "$RED 进程kill失败，也可能是因为守护进程重启了，进程列表如下：$RESET"
      psServerBinAllPath
    fi
  fi
}

function mySystemdServiceStop() {
  echo -e "$BOLD_WHITE 判断服务进程是否存在...$RESET"
  num=$(getServerBinAllPathNum)
  if [[ $num -eq 0 ]]; then
    echo -e "${GREEN}进程不存在，无需处理...$RESET"
  else
    echo -e "${GREEN}进程存在$RESET"
    echo -e "=========================== $GREEN 进程存在,stop...$RESET ==========================="
    echo  "开始stop..."
    oldPid=$(cat "$PID_FILE")
    echo -e "$RED 旧进程id： $oldPid $RESET"
    kill -9 "$oldPid"
    echo "停止完成"
    num=$(getServerBinAllPathNum)
    if [[ "$num" -eq 0 ]]; then
      echo  -e "${GREEN}进程kill成功，现在不存在...$RESET"
    else
      echo  -e "$RED 进程kill失败，进程列表如下：$RESET"
      # shellcheck disable=SC2009
      psServerBinAllPath
    fi
  fi
}

function myDevStop() {
  echo -e "$BOLD_WHITE 判断进程是否存在...$RESET"
  # shellcheck disable=SC2126
  # shellcheck disable=SC2046
  # shellcheck disable=SC2006
  # shellcheck disable=SC2009
  num=$(ps aux | grep `cat "$PID_FILE"` | grep -c -v grep)
  if [[ "$num" -eq 0 ]]; then
    echo -e "${GREEN}进程不存在，无需处理...$RESET"
  else
    echo  -e "${GREEN}进程存在，进程列表如下：$RESET"
    # shellcheck disable=SC2009
    ps aux | grep -v ".log" | grep -v tail | grep -v grep | grep --color "$APP_BIN_NAME"
    echo  -e "${GREEN}开始杀死进程...$RESET"
    # shellcheck disable=SC2046
    kill -TERM $(cat "$PID_FILE")
    sleep 2
    # shellcheck disable=SC2046
    # shellcheck disable=SC2006
    # shellcheck disable=SC2009
    num1=$(ps aux | grep `cat "$PID_FILE"` | grep -c -v grep)
    if [[ "$num1" -eq 0 ]]; then
      echo  -e "${GREEN}进程kill成功，现在不存在...$RESET"
    else
      echo  -e "$RED 进程kill失败，进程列表如下：$RESET"
      # shellcheck disable=SC2009
      ps aux | grep -v ".log" | grep -v tail | grep -v grep | grep --color "$APP_BIN_NAME"
    fi
  fi
}

if [[ "$env" == "dev" ]]; then
  myDevStop
elif [[ "$env" == "test" || "$env" == "prod" ]]; then

  if [[ "$damonMode" == "supervisor" ]]; then
    mySupervisorServiceStop
  elif [[ "$damonMode" == "systemd" ]]; then
    mySystemdServiceStop
  fi
fi
